var href = window.location.href;
let bodyContent = "<div class='crawl-btn-auto'>随机选择</div>";
bodyContent += " <div class='crawl-btn'>提取答案</div>";
bodyContent += " <div class='crawl-btn-answer'>自动考试</div>";
bodyContent += " <div class='crawl-btn-clear'>清除缓存</div>";
// bodyContent += " <div class='crawl-btn-clear0'>清除缓存1</div>";
// bodyContent += " <div class='crawl-btn-clear'>清除缓存2</div>";
if (href.includes("qingshuxuetang")) {
	$('body').append(bodyContent);
}

const HOST = "https://150.158.52.132:8099"
// const HOST = "https://127.0.0.1:8443"

const OPTIONS = ['A', 'B', 'C', 'D', '正确', '错误']

//自动选择
$('.crawl-btn-auto').click(function () {
	var questionArr = $(".question-detail-container");
	for (var i = 0; i < questionArr.length; i++) {
		var labelArr = $(questionArr[i]).find("label[class='option-label']");
		var random = getRandom();
		for (var j = 0; j < labelArr.length; j++) {
			if (random == j) {
				console.log("j", j)
				// console.log('ssss',$(labelArr[j]).val())
				$(labelArr[j]).click();
				break;
			}
		}
	}

	$(".submit_btn").click();
})

//获取随机数
function getRandom() {
	return Math.round(Math.random() * 1);
}
//清除答案
$('.crawl-btn-clear').click(function () {
	chrome.storage.local.remove('data', function () {
		alert("清除完成")
	});
	// checkNotification();
	// chrome.notification.create("test", {
	// 	type: 'basic',
	// 	iconUrl: 'iimages/fanqie.png',
	// 	title: '这是标题',
	// 	message: '您刚才点击了自定义右键菜单！'
	// });
})
//检查通知
function checkNotification() {
	if (!("Notification" in window)) {
		alert("This browser does not support desktop notification");
	}
	// check whether notification permissions have alredy been granted
	else if (Notification.permission === "granted") {
		// If it's okay let's create a notification
		new Notification("Granted!");
	}
	// Otherwise, ask the user for permission
	else if (Notification.permission !== 'denied') {
		Notification.requestPermission(function (permission) {
			// If the user accepts, let's create a notification
			if (permission === "granted") {
				new Notification("Request granted!");
			}
		});
	}
}

//提取答案
$('.crawl-btn').click(function () {


	console.log("href", href.includes("ViewQuiz"));
	if (!(href.includes("ViewQuiz"))) {
		return alert("请前往综合作业答案页或者期末考试答案页提取答案");
	}

	chrome.storage.local.get('data', function (result) {

		let remoteResult = {}

		$.get(HOST + '/v1/qingshu/answers', {}, function (res) {
			remoteResult = res
			console.log('answer res:', res);
		})
		var res = result.data
		res = res === {} || res === undefined || res === null ? {} : res
		res = Object.assign(res, remoteResult);

		// 得到题目的外部框
		var arr = $(".question-detail-container");
		// console.log('quertion-list.length:', arr.length)
		var data = res == undefined ? {} : res;
		for (var i = 0; i < arr.length; i++) {

			//答案
			let e0 = $(arr[i]).children()[0]
			let e1 = $(e0).children()[1]
			let e2 = $(e1).children()[0]
			let e3 = $(e2).children()[1]
			// 正确答案
			let rightAnswer = $(e3).text()


			//  题目
			let questName = $(arr[i]).children()[1]
			let questName1 = $(questName).children()[0]
			// 题目
			let questName2 = $(questName1).text()
			console.log('题目:', questName2)
			console.log('正确答案:', rightAnswer)

			let title = questName2.replace(/\s/g, "").replace(/^[0-9]{1,2}./, "")

			let mathcOptions = rightAnswer.match(/[A-Z]/g)
			console.log('mathcOptions:', mathcOptions)
			if(mathcOptions === null){
				data[title] = rightAnswer;
				continue
			}
			
			let answer = ''
			for (let mp = 0; mp < mathcOptions.length; mp++) {
				let tmpAnswer = '';
				// 选项
				let options = $(arr[i]).children()[2]
				let optionsIndex = OPTIONS.indexOf(mathcOptions[mp])
				// console.log('options', options)
				console.log('optionsIndex', optionsIndex)

				if (optionsIndex > 3) {
					console.log('optionsIndex > 3:', mathcOptions[mp])
					tmpAnswer = mathcOptions[mp]
				} else if (optionsIndex !== -1) {

					let option0 = $(options).children()[optionsIndex]
					// console.log('option0',option0)

					let option1 = $(option0).children()[1]
					// console.log('option1',option1)

					console.log('分割答案:', $(option1).text())
					tmpAnswer = $(option1).text()
				}
				if (tmpAnswer !== '') {
					tmpAnswer = tmpAnswer.replace(/\s/g, "").replace(/[A-Y]:/, "");
					if(answer === ''){
						answer += tmpAnswer
					}else{
						answer += "|*^*|" + tmpAnswer
					}
					
				}
			}

			data[title] = answer;

		}
		var dataBox = $("<div class='data-content' ></div>");
		var textWrap = $("<textarea class='text-wrap'>" + JSON.stringify(data, null, "\t") + "</textarea>");
		var textWrap1 = $("<p > 答案数量：" + Object.keys(data).length + "</textarea>");
		dataBox.append(textWrap1);

		dataBox.append(textWrap);
		chrome.storage.local.set({
			'data': data
		}, function () {
			console.log('保存成功');
		});

		// $.post('http://localhost:8080/v1/qingshu/submit', data, function (res) {
		// 	console.log('to server submit.', data)
		// }, 'json',Headers:{});

		$.ajax({
			type: 'POST',
			url: HOST + "/v1/qingshu/submit",
			data: JSON.stringify(data, null, "\t"),
			success: function (data) {
				console.log('to server submit.', data)
			},
			beforeSend: function (request) {
				request.setRequestHeader("Content-Type", "application/json");
			}

		})

		Modal.show({
			title: '提取结果',
			content: dataBox
		})
	})
})


//自动答题
$('.crawl-btn-answer').click(function () {
	$.get(HOST + '/v1/qingshu/answers', {}, function (data) {

		console.log('answer data:', data);



		var arr = $(".question-detail-container");
		chrome.storage.local.get('data', function (result) {

			var res = result.data
			var result = res == undefined ? {} : res;
			data = data === {} || data === undefined || data === null ? {} : data
			res = Object.assign(result, data);


			console.log('res:::', result)
			if (JSON.stringify(result) == '{}') {
				alert("答案缓存为空、请先在综合作业页面提取答案");
				return;
			}
			for (var i = 0; i < arr.length; i++) {

				//  题目
				let questName = $(arr[i]).children()[1]
				let questName1 = $(questName).children()[0]
				// 题目
				let questName2 = $(questName1).text()
				console.log('题目:', questName2)
				let title = questName2.replace(/\s/g, "").replace(/^[0-9]{1,2}./, "")
				var modelAnswer = result[title];
				modelAnswer = modelAnswer == undefined ? getModelAnswer(title, result) : modelAnswer;

				console.log("modelAnswer log", modelAnswer)
				// 兼容多选
				let modelAnswers = modelAnswer.split('|*^*|')

				for (let m = 0; m < modelAnswers.length; m++) {


					// 选项
					let options = $(arr[i]).children()[2]
					let option0 = $(options).children()
					// console.log('option0', option0.length)

					for (let y = 0; y < option0.length; y++) {
						// console.log('y', y)
						// console.log('option0[y]', option0[y])

						let option1 = $(option0[y]).children()[0]
						// console.log('option1', option1)

						let option2 = $(option1).children()[2]
						// console.log('option2', option2)

						// console.log('option:',$(option1).text())
						answer = $(option2).text()
						answer = answer.replace(/\s/g, "").replace(/[A-Y]:/, "");
						console.log('匹配到的答案', answer)
						console.log('题库答案', modelAnswers[m])



						if (answer == modelAnswers[m]) {
							$(option1).click()
							$(option2).css("background", "red")
						}

					}

				}
			}
			alert("自动答题完成、自动答题失败的题目已标红，请自行解决！！！");
		})
	})
});
//模糊搜索题目
function getModelAnswer(title, result) {
	for (let key in result) {
		if (title.includes(key)) {
			return result[key]
		}
	}
}

// 弹窗
~ function Modal() {
	var modal;

	if (this instanceof Modal) {
		this.init = function (opt) {
			modal = $("<div class='modal'></div>");
			var title = $("<div class='modal-title'>" + opt.title + "</div>");
			var close_btn = $("<span class='modal-close-btn'>X</span>");
			var content = $("<div class='modal-contents'></div>");
			var mask = $("<div class='modal-mask'></div>");
			close_btn.click(function () {
				modal.hide()
			})
			title.append(close_btn);
			content.append(title);
			content.append(opt.content);
			modal.append(content);
			modal.append(mask);
			$('body').append(modal);
		}
		this.show = function (opt) {
			if (modal) {
				modal.show();
			} else {
				var options = {
					title: opt.title || '标题',
					content: opt.content || ''
				}
				this.init(options)
				modal.show();
			}
		}
		this.hide = function () {
			modal.hide();
		}
	} else {
		window.Modal = new Modal()
	}
}()




// 在页面上插入代码
// 在配置文件中需设置"persistent": true, 因为事件页面不支持webrequest
console.log(11111, chrome.extension.getURL('ajax_interceptor.js'))
const script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', chrome.extension.getURL('ajax_interceptor.js'));
$('body').append(script);
